import { prisma } from '@/utils/backend/db'
import { HttpStatus } from '@/utils/httpStatus'
import * as jose from 'jose'
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'

export const POST = async (req: Request) => {
  try {
    const { username, password, code } = await req.json()

    // 验证验证码
    const cookieStore = await cookies()
    const captcha = cookieStore.get('captcha')

    if (!captcha || captcha.value.toLowerCase() !== code.toLowerCase()) {
      return NextResponse.json(
        {
          success: false,
          message: '验证码错误'
        },
        { status: HttpStatus.BAD_REQUEST }
      )
    }

    // 使用后删除验证码 cookie
    cookieStore.delete('captcha')

    // 查找用户
    const user = await prisma.user.findFirst({
      where: {
        username,
        password
      }
    })

    if (!user) {
      return NextResponse.json(
        {
          success: false,
          message: '用户名或密码错误'
        },
        { status: HttpStatus.BAD_REQUEST } // 请求参数错误
      )
    }

    // 生成 token
    const secret = new TextEncoder().encode(process.env.JWT_SECRET)
    const token =
      'Bearer ' +
      (await new jose.SignJWT(user).setProtectedHeader({ alg: 'HS256' }).setExpirationTime('7d').sign(secret))

    return NextResponse.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        userInfo: user
      }
    })
  } catch (error) {
    console.error('登录失败:', error)
    return NextResponse.json(
      {
        success: false,
        message: '服务器错误'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR } // Internal Server Error
    )
  }
}
